//
//  myMoneyPacketViewController.m
//  WZEfengAndEtong
//
//  Created by 李旭 on 16/9/21.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "myMoneyPacketViewController.h"
#import "FMDB.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "UIImageView+WebCache.h"
#import "CXmppRequestMgr.h"
#import "PopPasswordView.h"
#import "MoneyPasswordViewController.h"
#import "MBProgressHUD.h"
#import "outMoneyViewController.h"
#import "inMoneyViewController.h"
#import "bindViewController.h"
#import "myMoneyInfoViewController.h"
#import "JKAlertDialog.h"
typedef enum{
    deleteOpenId = 0,
    changePassword,
    replacePassword
} pwdType;
@interface myMoneyPacketViewController ()<UITableViewDelegate,UITableViewDataSource,PopPasswordViewDelegate>
@property(nonatomic,weak)UIImageView *topImageView;
@property(nonatomic,strong)CContactModel *curuser;
@property(nonatomic,weak)UILabel *moneyLabel;
@property(nonatomic,weak)UIView *buttonView;
@property(nonatomic,strong)NSArray *array;
@property(nonatomic,weak)UITableView *tableview;
@property(nonatomic,strong) PopPasswordView *passwordView;
@property(nonatomic)BOOL canBind;
@property(nonatomic,assign) pwdType type;
@end

@implementation myMoneyPacketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    self.curuser = [[[CContactMgr alloc]init] loadCurContact];
       [self.navigationItem setNewTitleCenter:@"我的钱包"];
    self.array = @[@"设置钱包密码",@"绑定提现账号",@"查看钱包明细"];
    [self configtopInterFace];
    [self configActionButton];
    [self configTableView];
    self.canBind = NO;
    
}
-(void)configtopInterFace
{
    UIImageView *imageview = [[UIImageView alloc]init];
    imageview.image = [UIImage imageNamed:@"moneybackGround"];
    self.topImageView = imageview;
    [self.view addSubview:imageview];
    [imageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(200);
    }];
    UIImageView *headImageView = [[UIImageView alloc]init];
     [headImageView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.curuser.UserID]] placeholderImage:[UIImage imageNamed:@"testHeader"]];
    headImageView.layer.cornerRadius = 40;
    headImageView.layer.masksToBounds = YES;
    [imageview addSubview:headImageView];
    [headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(80);
        make.top.mas_equalTo(20);
        make.centerX.mas_equalTo(imageview.centerX);
    }];
//    UILabel *label = [[UILabel alloc]init];
//    label.font = [UIFont systemFontOfSize:15];
//    label.text = @"金额";
//    label.textColor = [UIColor whiteColor];
//    label.textAlignment = NSTextAlignmentCenter;
//    [imageview addSubview:label];
//    [label mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(headImageView.mas_bottom).offset(10);
//        make.width.mas_equalTo(80);
//        make.height.mas_equalTo(30);
//        make.centerX.mas_equalTo(headImageView.centerX);
//    }];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitle:@"金额" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"purse"] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setImageEdgeInsets:UIEdgeInsetsMake(3, 3, 3, 10)];
    [imageview addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headImageView.mas_bottom).offset(10);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(30);
        make.centerX.mas_equalTo(headImageView.centerX);

    }];
    UILabel *moneyLabel = [[UILabel alloc]init];
    moneyLabel.textAlignment = NSTextAlignmentCenter;
    moneyLabel.font = [UIFont systemFontOfSize:20];
    moneyLabel.textColor = [UIColor whiteColor];
    moneyLabel.text = [NSString stringWithFormat:@"¥ ----"];
    self.moneyLabel = moneyLabel;
    [imageview addSubview:moneyLabel];
    [moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(button.mas_bottom).offset(0);
        make.right.left.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
}
-(void)configActionButton
{
    UIView *buttonView = [[UIView alloc]init];
    buttonView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:buttonView];
    [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topImageView.mas_bottom).offset(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(80);
    }];
    self.buttonView = buttonView;
    UIButton *toppedButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [toppedButton setImage:[UIImage imageNamed:@"充值icon"] forState:UIControlStateNormal];
    [toppedButton setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 15)];
    [toppedButton setTitleColor:RGBCOLORWITH16COLOR(0xcaafe) forState:UIControlStateNormal];
    [toppedButton setTitle:@"充值" forState:UIControlStateNormal];
    [toppedButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 0)];
    [toppedButton addTarget:self action:@selector(topped) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:toppedButton];
    [toppedButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(self.view.size.width/2-1);
    }];
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = RGBCOLORWITH16COLOR(0xe4e4e4);
    [buttonView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(50);
        make.center.mas_equalTo(buttonView.center);
    }];
    UIButton *outButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [outButton setImage:[UIImage imageNamed:@"提现icon"] forState:UIControlStateNormal];
    [outButton setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 15)];
    [outButton setTitleColor:RGBCOLORWITH16COLOR(0xffb535) forState:UIControlStateNormal];
    [outButton setTitle:@"取现" forState:UIControlStateNormal];
    [outButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 0)];
    [outButton addTarget:self action:@selector(moveMoneyToPacket) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:outButton];
    [outButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.mas_equalTo(0);
        make.left.mas_equalTo(view.mas_right).offset(0);
    }];
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = [UIColor grayColor];
    [buttonView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(0.4);
    }];
}
-(void)configTableView
{
    UITableView *tableview = [[UITableView alloc]init];
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableview.delegate = self;
    tableview.dataSource = self;
    [self.view addSubview:tableview];
    self.tableview = tableview;
    tableview.scrollEnabled = NO;
    [tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.buttonView.mas_bottom).offset(10);
    }];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在获取余额....";
    
    [[CXmppRequestMgr shareInstance] getPersonbalanceWithUserId:self.curuser.UserID successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"result"] isEqualToString:@"success"]) {
            NSString *openID = responseObject[@"openId"];
            if (openID.length>0) {
                self.canBind = NO;
            }
            else
            {
                self.canBind = YES;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud hide:YES];
                self.moneyLabel.text =[@"¥" stringByAppendingString:responseObject[@"money"]];
            });
        }
        else
        {
            [hud hide:YES];
            [MBProgressHUD showError:@"获取余额失败"];
        }
        
    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [hud hide:YES];
        [MBProgressHUD showError:@"获取余额失败"];
    }];
    
}
-(void)topped
{
    inMoneyViewController *inMoney = [inMoneyViewController sharedInstacet];
    inMoney.currentUser = self.curuser;
    [self.navigationController pushViewController:inMoney animated:YES];
}
-(void)moveMoneyToPacket
{
    if (self.canBind) {
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"提示" message:@"您未绑定账户，请先绑定提现账户"];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
        }];
        [alert show];
    }
    else
    {
    outMoneyViewController *outMoney = [[outMoneyViewController alloc]init];
    outMoney.blance = [self.moneyLabel.text substringFromIndex:1];
    [self.navigationController pushViewController:outMoney animated:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
#pragma mark---tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tableview == tableView) {
        return 50;
    }
    else
    {
        return 40;
    }
    }
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aaaa"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"aaaa"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSString *str = self.array[indexPath.row];
    cell.textLabel.text = str;
//    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.size.width, 0.5)];
//    view.backgroundColor = [UIColor grayColor];
//    if (indexPath.row == 0) {
//        [cell.contentView addSubview:view];
//    }
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(0, cell.height, self.view.size.width-20, 1)];
    view1.backgroundColor = RGBCOLORWITH16COLOR(0xe4e4e4);
    [cell.contentView addSubview:view1];
     return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.row == 0) {
        self.type = changePassword;
        self.passwordView=[[PopPasswordView alloc]initViewwithtype:@"no" andMoney:@"0"];
        self.passwordView.delegate=self;
        self.passwordView.type=@"no";
        [[UIApplication sharedApplication].keyWindow addSubview:self.passwordView];
    }else if (indexPath.row == 1){
        if (self.canBind) {
            bindViewController *bind = [[bindViewController alloc]init];
            [self.navigationController pushViewController:bind animated:YES];
        }
        else
        {
            JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"提示" message:@"您已经绑定过账号是否替换？"];
            [alert addButton:Button_OK withTitle:@"替换" handler:^(JKAlertDialogItem *item) {
                self.type = replacePassword;
                self.passwordView=[[PopPasswordView alloc]initViewwithtype:@"no" andMoney:@"0"];
                self.passwordView.delegate=self;
                self.passwordView.type=@"no";
                [[UIApplication sharedApplication].keyWindow addSubview:self.passwordView];
                
            }];
            [alert addButton:Button_CANCEL withTitle:@"解除绑定" handler:^(JKAlertDialogItem *item) {
                self.type = deleteOpenId;
                self.passwordView=[[PopPasswordView alloc]initViewwithtype:@"no" andMoney:@"0"];
                self.passwordView.delegate=self;
                self.passwordView.type=@"no";
                [[UIApplication sharedApplication].keyWindow addSubview:self.passwordView];
            }];
            [alert show];
        }
        }else if (indexPath.row == 2){
        myMoneyInfoViewController *mymoney = [[myMoneyInfoViewController alloc]init];
        [self.navigationController pushViewController:mymoney animated:YES];
    }
}
-(void)useStoreCode:(NSString *)code
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.passwordView removeFromSuperview];
    /*发网络请求 验证密码 如果成功*/
    /*失败就提示错误*/
    [[CXmppRequestMgr shareInstance]verificationPayPasswordWithUserId:self.curuser.UserID AndPassWord:code successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        [hud hide:YES];
        if ([responseObject[@"result"] isEqualToString:@"success"]) {
            if (self.type == changePassword) {
                 [self.navigationController pushViewController:[MoneyPasswordViewController alloc] animated:YES];
            }
            else if (self.type == replacePassword)
            {
                bindViewController *bind = [[bindViewController alloc]init];
                [self.navigationController pushViewController:bind animated:YES];

            }
            else
            {
               [[CXmppRequestMgr shareInstance] deleteOpenIdWithUserId:self.curuser.UserID successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                   if ([responseObject[@"result"] isEqualToString:@"success"]) {
                       [MBProgressHUD showSuccess:@"解除绑定成功"];
                       self.canBind = YES;
                    }
                   else
                   {
                       [MBProgressHUD showError:@"解除绑定失败"];
                   }
               } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                     [MBProgressHUD showError:@"解除绑定失败"];
               }];
            }
        }
       else
       {
           [MBProgressHUD showError:@"密码错误请重试"];
           NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
           [self tableView:self.tableview didSelectRowAtIndexPath:indexPath];
       }

    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
         [hud hide:YES];
        [MBProgressHUD showError:@"密码错误请重试"];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self tableView:self.tableview didSelectRowAtIndexPath:indexPath];
    }];

    
}
-(void)disAction
{
    [self.passwordView removeFromSuperview];
    
}

@end
